﻿using System;
using System.Collections;
using System.Text;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Linq;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Utilities;
using Microsoft.Office.Server;
using Microsoft.Office.Server.UserProfiles;
using Square.Activity;

namespace Square.ControlTemplates.Square
{
    public partial class MyFolder : UserControl
    {
        #region Variable
        private bool IsContentsUse = false;
        private bool IsSiteOwner = false;

        //화면에 랜더할 폴더와 문서를 가져올 사이트 주소
        private string strSiteUrl = string.Empty;

        //화면에 랜더할 폴더와 문서를 가져올 웹 이름과 주소
        private string strWebName = string.Empty;
        public string strCrrWebUrl = string.Empty;

        //화면에 랜더할 폴더와 문서를 가져올 리스트 주소와 아이디
        public string strListUrl = string.Empty;
        public string strListId = string.Empty;

        public string strPFolderUrl = string.Empty;

        //화면에 랜더할 트리메뉴의 HTML
        private string strTreeHtml = string.Empty;

        //폴더 및 문서 기본 Html 포맷
        private string strItemHtml = "<li class=\"{0} {1} drop_deactive\" id=\"{2}\">"
                                        + "<div class=\"dvItemBg\">"
                                        + "     <div class=\"colTypeImg\">{7}</div>"
                                        + "     <div class=\"colId\">{2}</div>"
                                        + "     <div class=\"colTitle\">{3}</div>"
                                        + "     <div class=\"colUrl\">{5}</div>"
                                        + "     <div class=\"dvItemInfo\">{6}</div>"
                                        + "     <div class=\"dvInfoLayer\">{8}</div>"
                                        + "     <div class=\"dvDepth\">{9}</div>"
                                        + "</div></li>";

        //폴더 및 문서 상세정보 레이어 Html 포맷
        private string strItemInfoHtml = "<div class='ui_docInfo'>{0}</div>";

        //아이템 형식 이미지 URL
        private string strTypeImgHtml = "<img alt='' src='{0}' />";

        //private string sfmCrrInfo = "<div class=\"crrFolderInfo\">- {0} Items<br /><div class=\"crrPermissionTitle\">- View Users</div><div class=\"crrPermissionUsers\">{1}</div></div>";
        private string sfmCrrInfo = "<div class=\"crrFolderInfo\">- {0} Items</div>";

        //문서 제목 클릭시 오피스로 오픈할 주소     
        //private string strDocOpenUrl = "<a onclick=\"editDocumentWithProgID2(\'{0}/{1}\', \'\', \'\', \'0\', \'{0}\', \'0\')>{2}</a>";
        private string strDocOpenUrl = "<a onmousedown=\"return VerifyHref(this,event,\'1\',\'SharePoint.OpenDocuments\',\'\')\" onclick=\"return DispEx(this,event,\'TRUE\',\'FALSE',\'{4}\',\'SharePoint.OpenDocuments.3\',\'1\',\'SharePoint.OpenDocuments\',\'\',\'\',\'\',\'{3}\',\'0\',\'0\',\'0x7fffffffffffffff\',\'\',\'\')\" onfocus=\"OnLink(this)\" href=\"{0}/{1}\">{2}</a>";

        //현재 사용자
        SPUser CrrUser = null;

        //쿠키에서 가져올 값
        private string strCookieValue = string.Empty;

        //목록보기 스타일
        public string strView_Detail = "liViewDetail_deactive";
        public string strView_Icon = "liViewIcon_deactive";

        public string strViewType = "view_Icon";

        //현재 위치를 담고 있을 문자열
        public string strCrrLocation = string.Empty;
        public string strCrrLocationEc = string.Empty;
        public string strCrrDepth = string.Empty;
        public string strCrrFolder = string.Empty;
        public string strCrrInfo = string.Empty;

        private string strNav = string.Empty;

        //폴더 정보를 담을 테이블
        DataTable table = new DataTable("dtFolders");
        DataColumn column;
        DataRow row;
        #endregion

        #region Properties

        #region private static bool HasCached(string strCookieName)
        /// <summary>
        /// 사용자 세션(쿠키) 정보의 존재여부 확인
        /// </summary>
        /// <returns>존재여부</returns>
        private static bool HasCached(string strCookieName)
        {
            if (System.Web.HttpContext.Current.Request.Cookies[strCookieName] == null)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        #endregion

        #region private string strFileType(string strFileUrl)
        /// <summary>
        /// 문서 아이템의 Url을 넘기면 파일 확장자를 반환한다.
        /// </summary>
        private string strFileType(string strFileUrl)
        {
            int intStart = strFileUrl.LastIndexOf('.');
            string fileType = string.Empty;
            fileType = strFileUrl.Substring(intStart + 1);
            return fileType;
        }
        #endregion

        #region private string strFileTypeImgUrl(string strFileType)
        /// <summary>
        /// 문서 아이템의 확장자를 넘기면 아이콘 Url을 반환한다.
        /// </summary>
        private string strFileTypeImgUrl(string strFileType)
        {
            string strImgUlr = string.Empty;
            //string strDefaultUrl = "/_layouts/Square/images/";
            string strDefaultUrl = "/_layouts/images/";

            string strImgName = string.Empty;

            switch (strFileType.ToLower())
            {
                #region test
                case "accdb": strImgName = "icaccdb.gif"; break;
                case "accdt": strImgName = "icaccdb.gif"; break;
                case "accdc": strImgName = "icaccdb.gif"; break;
                case "accde": strImgName = "icaccde.gif"; break;
                case "accdr": strImgName = "icaccde.gif"; break;
                case "asax": strImgName = "icasax.gif"; break;
                case "ascx": strImgName = "icascx.gif"; break;
                case "asmx": strImgName = "icasmx.gif"; break;
                case "asp": strImgName = "ichtm.gif"; break;
                case "aspx": strImgName = "ichtm.gif"; break;
                case "bmp": strImgName = "icbmp.gif"; break;
                case "cat": strImgName = "iccat.gif"; break;
                case "chm": strImgName = "icchm.gif"; break;
                case "config": strImgName = "icconfig.gif"; break;
                case "css": strImgName = "iccss.gif"; break;
                case "db": strImgName = "icdb.gif"; break;
                case "dib": strImgName = "icdib.gif"; break;
                case "disc": strImgName = "icdisc.gif"; break;
                case "doc": strImgName = "icdoc.png"; break;
                case "docm": strImgName = "icdocm.png"; break;
                case "docx": strImgName = "icdocx.png"; break;
                case "dot": strImgName = "icdot.png"; break;
                case "dotm": strImgName = "icdotm.png"; break;
                case "dotx": strImgName = "icdotx.png"; break;
                case "dvd": strImgName = "icdvd.gif"; break;
                case "dwp": strImgName = "icdwp.gif"; break;
                case "dwt": strImgName = "icdwt.gif"; break;
                case "eml": strImgName = "iceml.gif"; break;
                case "est": strImgName = "icest.gif"; break;
                case "fwp": strImgName = "icfwp.gif"; break;
                case "gif": strImgName = "icgif.gif"; break;
                case "hdp": strImgName = "ichdp.gif"; break;
                case "hlp": strImgName = "ichlp.gif"; break;
                case "hta": strImgName = "ichta.gif"; break;
                case "htm": strImgName = "ichtm.gif"; break;
                case "html": strImgName = "ichtm.gif"; break;
                case "htt": strImgName = "ichtt.gif"; break;
                case "inf": strImgName = "icinf.gif"; break;
                case "ini": strImgName = "icini.gif"; break;
                case "jfif": strImgName = "icjfif.gif"; break;
                case "jpe": strImgName = "icjpe.gif"; break;
                case "jpeg": strImgName = "icjpeg.gif"; break;
                case "jpg": strImgName = "icjpg.gif"; break;
                case "js": strImgName = "icjs.gif"; break;
                case "jse": strImgName = "icjse.gif"; break;
                case "log": strImgName = "iclog.gif"; break;
                case "master": strImgName = "icmaster.gif"; break;
                case "mht": strImgName = "icmht.gif"; break;
                case "mhtml": strImgName = "icmht.gif"; break;
                case "mpd": strImgName = "icmpd.gif"; break;
                case "mpp": strImgName = "icmpp.gif"; break;
                case "mps": strImgName = "icmps.gif"; break;
                case "mpt": strImgName = "icmpt.gif"; break;
                case "mpw": strImgName = "icmpw.gif"; break;
                case "mpx": strImgName = "icmpx.gif"; break;
                case "msg": strImgName = "icmsg.png"; break;
                case "msi": strImgName = "icmsi.gif"; break;
                case "msp": strImgName = "icmsp.gif"; break;
                case "ocx": strImgName = "icocx.gif"; break;
                case "odc": strImgName = "icodc.gif"; break;
                case "odp": strImgName = "icodp.png"; break;
                case "odt": strImgName = "icodt.png"; break;
                case "ods": strImgName = "icods.png"; break;
                case "one": strImgName = "icone.png"; break;
                case "onepkg": strImgName = "iconp.png"; break;
                case "onetoc2": strImgName = "icont.png"; break;
                case "png": strImgName = "icpng.gif"; break;
                case "pot": strImgName = "icpot.png"; break;
                case "potm": strImgName = "icpotm.png"; break;
                case "potx": strImgName = "icpotx.png"; break;
                case "ppa": strImgName = "icppa.png"; break;
                case "ppam": strImgName = "icppam.png"; break;
                case "ppt": strImgName = "icppt.png"; break;
                case "pptm": strImgName = "icpptm.png"; break;
                case "pptx": strImgName = "icpptx.png"; break;
                case "pps": strImgName = "icpps.png"; break;
                case "ppsdc": strImgName = "icppsdc.png"; break;
                case "ppsm": strImgName = "icppsm.png"; break;
                case "ppsx": strImgName = "icppsx.png"; break;
                case "psp": strImgName = "icpsp.gif"; break;
                case "psd": strImgName = "icbmp.gif"; break;
                case "ptm": strImgName = "icptm.gif"; break;
                case "ptt": strImgName = "icptt.gif"; break;
                case "pub": strImgName = "icpub.gif"; break;
                case "rdl": strImgName = "doc_sp16.gif"; break;
                case "rsapplication": strImgName = "newreport_sp.gif"; break;
                case "rsc": strImgName = "component_sp16.gif"; break;
                case "rsd": strImgName = "dataset_sp16.gif"; break;
                case "rsds": strImgName = "datasource.gif"; break;
                case "rtf": strImgName = "icrtf.gif"; break;
                case "smdl": strImgName = "model_sp16.gif"; break;
                case "stp": strImgName = "icstp.gif"; break;
                case "stt": strImgName = "icstt.gif"; break;
                case "thmx": strImgName = "icthmx.gif"; break;
                case "tif": strImgName = "ictif.gif"; break;
                case "tiff": strImgName = "ictiff.gif"; break;
                case "txt": strImgName = "ictxt.gif"; break;
                case "vbe": strImgName = "icvbe.gif"; break;
                case "vbs": strImgName = "icvbs.gif"; break;
                case "vdw": strImgName = "icvdw.gif"; break;
                case "vdx": strImgName = "icvdx.gif"; break;
                case "vsd": strImgName = "icvsd.gif"; break;
                case "vsl": strImgName = "icvsl.gif"; break;
                case "vss": strImgName = "icvss.gif"; break;
                case "vst": strImgName = "icvst.gif"; break;
                case "vsu": strImgName = "icvsu.gif"; break;
                case "vsw": strImgName = "icvsw.gif"; break;
                case "vsx": strImgName = "icvsx.gif"; break;
                case "vtx": strImgName = "icvtx.gif"; break;
                case "wdp": strImgName = "ichdp.gif"; break;
                case "webpart": strImgName = "icdwp.gif"; break;
                case "wm": strImgName = "icwm.gif"; break;
                case "wma": strImgName = "icwma.gif"; break;
                case "wmd": strImgName = "icwmd.gif"; break;
                case "wmp": strImgName = "icwmp.gif"; break;
                case "wms": strImgName = "icwms.gif"; break;
                case "wmv": strImgName = "icwmv.gif"; break;
                case "wmx": strImgName = "icwmx.gif"; break;
                case "wmz": strImgName = "icwmz.gif"; break;
                case "wsf": strImgName = "icwsf.gif"; break;
                case "xla": strImgName = "icxla.png"; break;
                case "xlam": strImgName = "icxlam.png"; break;
                case "xls": strImgName = "icxls.png"; break;
                case "xlsb": strImgName = "icxlsb.png"; break;
                case "xlsm": strImgName = "icxlsm.png"; break;
                case "xlsx": strImgName = "icxlsx.png"; break;
                case "xlt": strImgName = "icxlt.png"; break;
                case "xltb": strImgName = "icxltx.gif"; break;
                case "xltm": strImgName = "icxltm.png"; break;
                case "xltx": strImgName = "icxltx.png"; break;
                case "xml": strImgName = "icxml.gif"; break;
                case "xps": strImgName = "icxps.gif"; break;
                case "xsd": strImgName = "icxsd.gif"; break;
                case "xsl": strImgName = "icxsl.gif"; break;
                case "xsn": strImgName = "icxsn.gif"; break;
                case "xslt": strImgName = "icxslt.gif"; break;
                case "zip": strImgName = "iczip.gif"; break;
                #endregion

                default: strImgName = "icdoc.png"; break;
            }

            strImgUlr = strDefaultUrl + strImgName;

            return strImgUlr;
        }
        #endregion

        #region private string strConvertToString(object _value)
        /// <summary>
        /// object를 string로 변환해 준다.
        /// </summary>
        /// <param name="_value"></param>
        /// <returns></returns>
        private string strConvertToString(object _value)
        {
            string strValue = string.Empty;

            try
            {
                if (_value != null)
                {
                    strValue = _value.ToString();
                }
            }
            catch (Exception)
            {
            }

            return strValue;
        }
        #endregion

        #region public static string GetTextResource(string strResource, string strName)
        /// <summary>
        /// Global Resource 에서 매개변수로 넘겨진 키값으로 리소스 값을 가져온다. 오버로드 메서드 #2
        /// </summary>
        /// <param name="resxFile">리소스 파일명</param>
        /// <param name="strKey">리소스 키</param>
        /// <param name="uiLanguage">언어 정수값 예:1033 - 영어</param>
        /// <returns>키 값에 해당하는 리소스 값</returns>
        public static string GetTextResource(string resxFile, string strKey)
        {
            string str = SPUtility.GetLocalizedString(string.Format("$Resources:{0},{1}", resxFile, strKey), resxFile, 1033);
            return str != null ? str : "";
        }
        #endregion

        #endregion

        #region protected void Page_Load(object sender, EventArgs e)
        /// <summary>
        /// 페이지 로드
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                #region Get Default Info
                CrrUser = SPContext.Current.Web.AllUsers[HttpContext.Current.User.Identity.Name.ToString()];

                string strCrrAccount = string.Empty;
                if (Request.QueryString["accountname"] != null)
                    strCrrAccount = Request.QueryString["accountname"].ToString();
                if (strCrrAccount.ToLower().Equals(HttpContext.Current.User.Identity.Name.ToLower()))
                    IsSiteOwner = true;
                if (IsSiteOwner)
                {
                    this.dvDocAdd.Visible = true;
                    this.dvFolderAdd.Visible = true;
                    this.liFolderDelete.Visible = true;
                }

                ServerContext context = ServerContext.GetContext(SPContext.Current.Site);
                UserProfileManager profileManager = new UserProfileManager(context);
                UserProfile profile = profileManager.GetUserProfile(strCrrAccount);

                //My Contents Use?
                if (profile.PersonalSite != null) IsContentsUse = true;
                #endregion                                

                #region My contents 사용여부별로 표시를 달리한다.
                if (IsContentsUse)
                {
                    #region Get Personal Info
                    string personUrl = profile.PersonalSite.Url;
                    strSiteUrl = personUrl;
                    strWebName = profile.PersonalSite.OpenWeb().Title;
                    //strCrrWebUrl = personUrl;
                    strCrrWebUrl = profile.PersonalSite.ServerRelativeUrl;
                    strListUrl = personUrl + "/Personal%20Documents/Forms/AllItems.aspx";

                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        using (SPSite _site = new SPSite(strSiteUrl))
                        {
                            using (SPWeb _web = _site.OpenWeb())
                            {
                                strListId = _web.GetList(strListUrl).ID.ToString();
                            }
                        }
                    });
                    #endregion

                    if (!IsPostBack)
                    {
                        Default();
                    }
                }
                else
                {
                    this.dvAll.Visible = false;
                    this.ltNoContents.Text = "<div class='dvNoContents'><img alt='' src='/_layouts/Square/images/NoContents.png'></div>";
                }
                #endregion
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region Method

        #region private void Default()
        /// <summary>
        /// 
        /// </summary>
        private void Default()
        {
            try
            {
                SetNavigation();
                GetData();
                this.lbViewState.Text = "url : " + strConvertToString(ViewState["crrfolder_location"]) + " / depth : " + strConvertToString(ViewState["crrfolder_depth"]);
                this.lbViewState.Visible = false;
                
                this.hdfolderLocation.Value = strConvertToString(ViewState["crrfolder_location"]);
                this.hdfolderDepth.Value = strConvertToString(ViewState["crrfolder_depth"]);                

                strCrrDepth = strConvertToString(ViewState["crrfolder_depth"]);

                #region 상위로 이동 폴더 셋팅
                if (ViewState["crrfolder_depth"] == null)
                {
                    this.liNavBtn.Visible = false;
                }
                else
                {
                    if (ViewState["crrfolder_depth"].ToString() == "0")
                    {
                        this.liNavBtn.Visible = false;
                    }
                    else
                    {
                        this.liNavBtn.Visible = true;
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion        

        #region Navigation

        #region private void SetNavigation()
        /// <summary>
        /// 폴더의 네비게이션을 생성한다.
        /// </summary>
        private void SetNavigation()
        {
            #region Set FolderTable Column

            #region 컬럼 - 자동증가 ID
            column = new DataColumn();
            column.DataType = System.Type.GetType("System.Int32");
            column.ColumnName = "ID";
            column.AutoIncrement = true;
            //column.Caption = "ParentID";
            column.ReadOnly = true;
            column.Unique = true;
            table.Columns.Add(column);
            #endregion

            #region 컬럼 - title
            column = new DataColumn();
            column.DataType = System.Type.GetType("System.String");
            column.ColumnName = "title";
            column.AutoIncrement = false;
            //column.Caption = "ChildItem";
            column.ReadOnly = false;
            column.Unique = false;
            table.Columns.Add(column);
            #endregion

            #region 컬럼 - depth
            column = new DataColumn();
            column.DataType = System.Type.GetType("System.Int32");
            column.ColumnName = "depth";
            column.AutoIncrement = false;
            //column.Caption = "ID";
            column.ReadOnly = false;
            column.Unique = false;
            table.Columns.Add(column);
            #endregion

            #region 컬럼 - html
            column = new DataColumn();
            column.DataType = System.Type.GetType("System.String");
            column.ColumnName = "url";
            column.AutoIncrement = false;
            //column.Caption = "ChildItem";
            column.ReadOnly = false;
            column.Unique = false;
            table.Columns.Add(column);
            #endregion

            #endregion          

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite _site = new SPSite(strListUrl))
                {
                    using (SPWeb _web = _site.OpenWeb(strListUrl))
                    {
                        SPList _spList = _web.GetList(strListUrl);

                        GetFolderData(_spList.RootFolder, _spList.RootFolder, 0);

                        #region 뷰스테이트 null 경우 처리 - 리스트의 루트폴더로 설정한다.
                        if (ViewState["crrfolder_location"] == null)
                        {
                            ViewState["crrfolder_location"] = _spList.RootFolder.Url;
                        }
                        if (ViewState["crrfolder_depth"] == null)
                        {
                            ViewState["crrfolder_depth"] = "0";
                        }
                        #endregion

                        strCrrLocation = strConvertToString(ViewState["crrfolder_location"]);
                        strCrrLocationEc = System.Web.HttpUtility.UrlEncode(strCrrLocation);

                        #region ViewState["crrfolder_location"]에 따라 폴더의 아이템 가져오는 방식을 달리한다.
                        if (ViewState["crrfolder_location"] == _spList.RootFolder.Url)
                        {
                            if (ViewState["crrfolder_depth"] == "0")
                            {
                                strFolderItem(_spList.RootFolder, _spList.RootFolder, 0);
                            }
                        }
                        else
                        {
                            SPFolder CrrFolder = _web.GetFolder(strConvertToString(ViewState["crrfolder_location"]));

                            if (CrrFolder != null)
                            {
                                strFolderItem(_spList.RootFolder, CrrFolder, 0);
                            }
                        }
                        #endregion
                    }
                }
            });

            strNav = "<ul class=\"jsddm\">" + strNav + "</ul>";
            this.dvNavigation.InnerHtml = strNav;
        }
        #endregion

        #region private void GetFolderData(SPFolder _rootFolder, SPFolder spFolder, int iDepth)
        /// <summary>
        /// 폴더 정보(하위 폴더 포함, title/url/depth)를 DataTable에 넣는다.
        /// </summary>
        private void GetFolderData(SPFolder _rootFolder, SPFolder spFolder, int iDepth)
        {
            if (spFolder.Name.ToLower() != "forms")
            {
                row = table.NewRow();
                row["title"] = spFolder.Name;
                row["depth"] = iDepth;
                row["url"] = spFolder.Url;
                table.Rows.Add(row);

                if (spFolder.SubFolders.Count > 0)
                {
                    foreach (SPFolder _tFolder in spFolder.SubFolders)
                    {
                        GetFolderData(_rootFolder, _tFolder, iDepth + 1);
                    }
                }
            }
        }
        #endregion

        #region private void strFolderItem(SPFolder _rootFolder, SPFolder spFolder)
        /// <summary>
        /// SPFolder를 이용해 네비게이션에 표시할 HTML을 그린다.
        /// </summary>
        private void strFolderItem(SPFolder _rootFolder, SPFolder spFolder, int intRevertDepth)
        {
            if (spFolder.Name.ToLower() != "forms")
            {
                string strDepth = string.Empty;

                foreach (DataRow _row in table.Rows)
                {
                    if (strConvertToString(spFolder.Url) == strConvertToString(_row["url"]))
                    {
                        strDepth = strConvertToString(_row["depth"]);
                        break;
                    }
                }

                if (intRevertDepth == 0) //0이 말단 폴더(현재 폴더)이다. 루트로 갈수록 증가한다!
                {
                    strNav = string.Format("<li class='nav_li'><div class='nav_li_url'>" + strConvertToString(spFolder.Url) + "</div><div class='nav_li_depth'>" + strDepth + "</div><a class='NavPadding' href=\"{0}\">{1}</a>{2}</li>", "javascript:location_change('" + strConvertToString(spFolder.Url) + "', '" + strDepth + "')", strConvertToString(spFolder.Name), strSubFolders(spFolder, strDepth)) + strNav;

                    //현재 폴더 정보(아이템 카운트)
                    strCrrInfo = string.Format(sfmCrrInfo, spFolder.ItemCount);
                }
                else
                    strNav = string.Format("<li class='nav_li'><div class='nav_li_url'>" + strConvertToString(spFolder.Url) + "</div><div class='nav_li_depth'>" + strDepth + "</div><a class='NavPadding' href=\"{0}\">{1}&nbsp;&nbsp;></a>{2}</li>", "javascript:location_change('" + strConvertToString(spFolder.Url) + "', '" + strDepth + "')", strConvertToString(spFolder.Name), strSubFolders(spFolder, strDepth)) + strNav;

                if (spFolder.ParentFolder.Exists && !string.IsNullOrEmpty(spFolder.ParentFolder.Url) && spFolder.ParentFolder != _rootFolder)
                    strFolderItem(_rootFolder, spFolder.ParentFolder, intRevertDepth + 1);
            }
        }
        #endregion

        #region private string strSubFolders(SPFolder _fol, string strDepth)
        /// <summary>
        /// 네비게이션에 표시되는 Folder(Depth 별)를 받아 DataTable row중 동일한 Depth의 폴더들을 서브 메뉴 html로 만들어 반환한다.
        /// </summary>
        /// <param name="_fol"></param>
        /// <returns></returns>
        private string strSubFolders(SPFolder _fol, string strDepth)
        {
            StringBuilder sbSubfols = new StringBuilder();

            sbSubfols.Append("<ul>");

            for (int f = 0; f < table.Rows.Count; f++)
            {
                DataRow _fRow = table.Rows[f];

                if (strConvertToString(_fRow["depth"]) == strDepth)
                {
                    if (strConvertToString(_fRow["url"]) != _fol.Url)
                    {
                        sbSubfols.AppendFormat("<li><a class='NavPadding' href=\"{0}\">{1}</a></li>", "javascript:location_change('" + strConvertToString(_fRow["url"]) + "', '" + strDepth + "')", strConvertToString(_fRow["title"]));
                    }
                }
            }

            sbSubfols.Append("</ul>");

            return sbSubfols.ToString();
        }
        #endregion

        #endregion

        #region Contents

        #region private void GetData()
        /// <summary>
        /// 리스트로 부터 폴더 및 아이템을 가져와 화면에 랜더한다.
        /// </summary>
        private void GetData()
        {
            #region ViewState를 통한 목록보기 셋팅, 버튼 활성화 처리
            if (ViewState["type_listview"] == null)
            {
                ViewState["type_listview"] = "thumb";
                strView_Icon = "liViewIcon_active";
                strViewType = "View_Icon";
            }
            else
            {
                if (ViewState["type_listview"].ToString() == "thumb")
                {
                    strView_Icon = "liViewIcon_active";
                    strViewType = "View_Icon";
                }
                else if (ViewState["type_listview"].ToString() == "detail")
                {
                    strView_Detail = "liViewDetail_active";
                    strViewType = "View_Detail";
                }
            }
            strCookieValue = ViewState["type_listview"].ToString();
            #endregion

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite _site = new SPSite(strListUrl))
                {
                    using (SPWeb _web = _site.OpenWeb(strListUrl))
                    {
                        #region Get items from list
                        SPList spList = _web.GetList(strListUrl);
                        SPListItemCollection dtItems = PageListItemsReturn(spList);
                        #endregion

                        #region 아이템이 있는 경우(리스트아이템컬렉션) Html을 만든다.
                        if (dtItems != null)
                        {
                            if (dtItems.Count > 0)
                            {
                                StringBuilder _sbFolders = new StringBuilder();
                                StringBuilder _sbDocs = new StringBuilder();

                                foreach (SPListItem drItem in dtItems)
                                {
                                    if (drItem.DoesUserHavePermissions(CrrUser, SPBasePermissions.ViewListItems))
                                    {
                                        string strDepth = string.Empty;

                                        #region 아이템의 사이트주소/웹주소/리스트주소/폴더명/문서아이디 설정
                                        string strTempSiteUrl = drItem.ParentList.ParentWeb.Site.Url;
                                        string strTempWebUrl = drItem.ParentList.ParentWeb.ServerRelativeUrl;
                                        string strTempListUrl = drItem.ParentList.DefaultViewUrl;
                                        string strTempFolderName = string.Empty;
                                        if (drItem.Folder != null)
                                        {
                                            strTempFolderName = drItem.Folder.Name;
                                        }
                                        string strTempDocID = drItem.ID.ToString();
                                        string strItemInfo = strTempSiteUrl + "^" + strTempWebUrl + "^" + strTempListUrl + "^" + strTempFolderName + "^" + strTempDocID;
                                        #endregion

                                        #region 폴더
                                        if (drItem["ContentType"].ToString() == "폴더" || drItem["ContentType"].ToString().ToLower() == "folder")
                                        {
                                            for (int s = 0; s < table.Rows.Count; s++)
                                            {
                                                if (drItem.Url.ToString() == strConvertToString(table.Rows[s]["url"]))
                                                {
                                                    strDepth = strConvertToString(table.Rows[s]["depth"]);
                                                    break;
                                                }
                                            }

                                            _sbFolders.AppendFormat(
                                                strItemHtml
                                                , "folder"
                                                , strCookieValue
                                                , drItem.ID.ToString()
                                                , "<div class='dvFolderCnt'>" + drItem.Folder.ItemCount + "</div>" + drItem.DisplayName.ToString()
                                                , drItem.Name.ToString()
                                                , drItem.Url.ToString()
                                                , strItemInfo
                                                , string.Format(strTypeImgHtml, "/_layouts/Square/images/folder_icon.png") //icon_doc.png
                                                , string.Format(strItemInfoHtml
                                                , "<img alt='' src='/_layouts/Square/images/btn_set.png' class='btn_set' onclick=\"javascript:openSetPage(\'"
                                                    + HttpUtility.UrlEncode(_web.Url)
                                                    + "\', \'" + HttpUtility.UrlEncode(drItem.ParentList.ID.ToString())
                                                    + "\', \'" + HttpUtility.UrlEncode(drItem.ID.ToString())
                                                    + "\', \'" + HttpUtility.UrlEncode(drItem.Folder.ToString())
                                                    + "\', \'" + HttpUtility.UrlEncode(drItem.Folder.ParentFolder.Url.ToString())
                                                    + "\');\""
                                                    + "/>"
                                                    //+ "<br /><br />"
                                                    + "<b>" + drItem.DisplayName + "</b><br />"
                                                    + "Author : " + strConvertToString(drItem["Author"]).Split('#')[1].ToString() + "<br />"
                                                    + "Editor : " + strConvertToString(drItem["Editor"]).Split('#')[1].ToString() + "<br />"
                                                    + "Created : " + strConvertToString(drItem["Created"]) + "<br />"
                                                    + "Modified : " + strConvertToString(drItem["Modified"]) + "<br />"
                                                    + "Item Count : " + drItem.Folder.ItemCount
                                                    )
                                                , strDepth
                                                );
                                        }
                                        #endregion

                                        #region 문서
                                        else
                                        {
                                            _sbDocs.AppendFormat(
                                                strItemHtml
                                                , "doc"
                                                , strCookieValue
                                                , drItem.ID.ToString()
                                                , "<div class='dvFileType'>" + string.Format(strTypeImgHtml, strFileTypeImgUrl(strFileType(drItem.Url))) + "</div>" + string.Format(strDocOpenUrl, strCrrWebUrl, drItem.Url.ToString(), drItem.DisplayName.ToString(), "1", "FALSE") //ppt의 경우 TRUE
                                                , drItem.Name.ToString()
                                                , drItem.Url.ToString()
                                                , strItemInfo
                                                , string.Format(strTypeImgHtml, strFileTypeImgUrl(strFileType(drItem.Url)))
                                                , string.Format(strItemInfoHtml
                                                    , "<b>" + drItem.Name + "</b><br />"
                                                    + "Author : " + strConvertToString(drItem["Author"]).Split('#')[1].ToString() + "<br />"
                                                    + "Editor : " + strConvertToString(drItem["Editor"]).Split('#')[1].ToString() + "<br />"
                                                    + "Created : " + strConvertToString(drItem["Created"]) + "<br />"
                                                    + "Modified : " + strConvertToString(drItem["Modified"]) + "<br />"
                                                    )
                                                , strDepth
                                                );
                                        }
                                        #endregion
                                    }       
                                }

                                this.folders.InnerHtml = _sbFolders.ToString();
                                this.docs.InnerHtml = _sbDocs.ToString();
                            }
                            else
                            {
                                this.folders.InnerHtml = string.Empty;
                                this.docs.InnerHtml = string.Empty;
                            }
                        }
                        #endregion
                    }
                }
            });          
        }
        #endregion

        #region private SPListItemCollection PageListItemsReturn(SPList spList)
        /// <summary>
        /// 페이징에 따른 ListItemCollection을 리턴한다.
        /// </summary>
        /// <param name="nPageNum"></param>
        /// <param name="twList"></param>
        /// <returns></returns>
        private SPListItemCollection PageListItemsReturn(SPList spList)
        {
            string strCrrFolderUrl = strConvertToString(ViewState["crrfolder_location"]);

            SPQuery spTempQuery = new SPQuery();
            spTempQuery.Query = "<Where></Where>";
            spTempQuery.RowLimit = Convert.ToUInt32(100);

            if (string.IsNullOrEmpty(strCrrFolderUrl))
            {
                spTempQuery.Folder = spList.RootFolder;
                ViewState["crrfolder_location"] = spList.RootFolder.Url;

                strCrrFolder = spList.RootFolder.ServerRelativeUrl;

                if (ViewState["crrfolder_depth"] == null)
                {
                    //0 = 루트
                    ViewState["crrfolder_depth"] = "0";
                }
            }
            else
            {
                spTempQuery.Folder = SetFolderQuery(spList.ParentWeb, strCrrFolderUrl);

                strCrrFolder = spTempQuery.Folder.ServerRelativeUrl;
            }

            SPListItemCollection splistItems = spList.GetItems(spTempQuery);
            return splistItems;
        }
        #endregion

        #region private SPFolder SetFolderQuery()
        /// <summary>
        /// SPWeb과 Folder Url로 SPFolder을 반환한다. 
        /// </summary>
        /// <returns></returns>
        private SPFolder SetFolderQuery(SPWeb _web, string strUrl)
        {
            SPFolder _folder = null;

            _folder = _web.GetFolder(strUrl);

            return _folder;
        }
        #endregion

        #endregion

        #region applySetting
        /// <summary>
        /// UI단에서 이루어지는 문서 이동, 폴더 생성 등의 설정을 적용한다. - 버튼 클릭 시 실행된다.
        /// </summary>
        /// <param name="strEventType">이벤트타입 1:아이템이동, 2:아이템복사, 3:폴더생성</param>
        /// <param name="strFromSiteUrl">문서를 가져올 사이트 주소</param>
        /// <param name="strFromWebName">문서를 가져올 웹 이름</param>
        /// <param name="strFromListUrl">문서를 가져올 리스트 주소</param>
        /// <param name="strFromDocID">가져올 문서 아이디</param>
        /// <param name="strToSite">문서를 옮길 사이트 주소</param>
        /// <param name="strToWebName">문서를 옮길 웹 이름</param>
        /// <param name="strToList">문서를 옮길 리스트 주소</param>
        /// <param name="strToFolder">문서를 옮길 폴더명</param>
        private void applySetting(string strEventType, string strFromSiteUrl, string strFromWebName, string strFromListUrl, string strFromDocID, string strToSiteUrl, string strToWebName, string strToListUrl, string strToFolderName)
        {
            #region Log Setting
            bool bSave = false;
            SquareActivities aType = new SquareActivities();
            SquareActivityHelper sHelper = new SquareActivityHelper();
            #endregion

            //임시로 예외 처리
            try
            {
                ViewState["crrfolder_location"] = null;
                ViewState["crrfolder_depth"] = null;

                ViewState["crrfolder_location"] = strConvertToString(this.hdfolderLocation.Value);
                ViewState["crrfolder_depth"] = strConvertToString(this.hdfolderDepth.Value);

                SPUtility.ValidateFormDigest();

                #region 문서 이동
                if (strEventType == "1")
                {
                    int intFromDocID = Convert.ToInt32(strFromDocID);
                    string strDocFileName = string.Empty;
                    byte[] fileBytes = null;
                    SPList sourceDocuments = null;
                    SPListItem currentSourceDocument = null;
                    string strDocName = string.Empty;
                    string strFromFolder = string.Empty;
                    string strToFolder = string.Empty;

                    #region //문서를 가져올 사이트와 웹의 아이디를 가져온다. (fSiteId, fWebId)
                    //Guid fSiteId = Guid.NewGuid();
                    //Guid fWebId = Guid.NewGuid();
                    //using (SPSite oSite = new SPSite(strFromSiteUrl))
                    //{
                    //    using (SPWeb oRoot = oSite.OpenWeb(strFromWebName))
                    //    {
                    //        fSiteId = oSite.ID;
                    //        fWebId = oRoot.ID;
                    //    }
                    //}
                    #endregion

                    #region //문서를 옮길 사이트와 웹의 아이디를 가져온다. (tSiteId, tWebId)
                    //Guid tSiteId = Guid.NewGuid();
                    //Guid tWebId = Guid.NewGuid();
                    //using (SPSite oSite = new SPSite(strToSiteUrl))
                    //{
                    //    using (SPWeb oRoot = oSite.OpenWeb(strToWebName))
                    //    {
                    //        tSiteId = oSite.ID;
                    //        tWebId = oRoot.ID;
                    //    }
                    //}
                    #endregion

                    #region From
                    using (SPSite fSite = new SPSite(strListUrl))
                    {
                        using (SPWeb sourceWeb = fSite.OpenWeb(strListUrl))
                        {
                            sourceDocuments = sourceWeb.GetList(strFromListUrl); //가져올 리스트
                            currentSourceDocument = sourceDocuments.GetItemById(intFromDocID); //이동할 문서

                            if (currentSourceDocument.Folder == null)
                            {
                                strFromFolder = currentSourceDocument.ParentList.RootFolder.Name;
                            }
                            else
                            {
                                strFromFolder = currentSourceDocument.Folder.Name;
                            }

                            fileBytes = currentSourceDocument.File.OpenBinary();
                            strDocFileName = currentSourceDocument.File.Name;
                        }
                    }
                    #endregion

                    #region To
                    using (SPSite tSite = new SPSite(strListUrl)) //보낼 사이트
                    {
                        using (SPWeb destinationWeb = tSite.OpenWeb(strListUrl)) //보낼 웹
                        {
                            SPList destinationDocuments = destinationWeb.GetList(strToListUrl); //보낼 리스트
                            //ClearList(destinationDocuments);
                            //여기서 strToFolderName 을 통해 루트 폴더 이외의 폴더를 지정하게 한다.
                            string strToFolderUrl = destinationDocuments.RootFolder.Url + "/";

                            for (int f = 0; f < destinationDocuments.Folders.Count; f++)
                            {
                                if (destinationDocuments.Folders[f].Name == strToFolderName)
                                {
                                    strToFolder = strToFolderName;
                                    strToFolderUrl = destinationDocuments.Folders[f].Url + "/";
                                    break;
                                }
                            }

                            const bool OverwriteDestinationFile = true;
                            string relativeDestinationUrl = strToFolderUrl + strDocFileName;
                            SPFile destinationFile = ((SPDocumentLibrary)destinationDocuments).RootFolder.Files.Add(relativeDestinationUrl, fileBytes, OverwriteDestinationFile);
                        }
                    }
                    #endregion

                    #region 문서이동일 경우 - 기존 아이템 삭제, 리스트 업데이트
                    strDocName = currentSourceDocument.DisplayName;
                    currentSourceDocument.Delete();
                    sourceDocuments.Update();
                    #endregion

                    #region 문서복사인 경우 - 기존 아이템 유지 - 주석처리
                    //currentSourceDocument.Delete();
                    //sourceDocuments.Update();
                    #endregion

                    #region Log
                    aType = SquareActivities.SquareDocMove;
                    bSave = sHelper.SaveActivity(this.Page, aType, string.Format(GetTextResource("SquareRes", "SquareDocMove"), strDocName, strFromFolder, strToFolder)); //"xxx님이 xxx 문서를 xxx 위치로 이동하였습니다.");
                    #endregion
                }
                #endregion
                #region //문서 복사
                else if (strEventType == "2")
                {
                    #region Log
                    aType = SquareActivities.SquareDocCopy;
                    bSave = sHelper.SaveActivity(this.Page, aType, GetTextResource("SquareRes", "SquareDocCopy")); //"xxx님이 xxx 문서를 복사하였습니다.");
                    #endregion
                }
                #endregion
                #region 폴더 생성
                else if (strEventType == "3")
                {
                    using (SPSite _site = new SPSite(strListUrl))
                    {
                        using (SPWeb _web = _site.OpenWeb(strListUrl))
                        {
                            SPList _list = _web.GetList(strListUrl);
                            SPFolder CrrFolder = _web.GetFolder(strConvertToString(ViewState["crrfolder_location"]));

                            if (CrrFolder != null)
                            {
                                bool IsExsit = false;

                                #region Same Name Folder Exist Check
                                if (CrrFolder.SubFolders.Count > 0)
                                {
                                    foreach (SPFolder _folder in CrrFolder.SubFolders)
                                    {
                                        if (_folder.Name == strToFolderName)
                                        {
                                            IsExsit = true;
                                            break;
                                        }
                                    }
                                }
                                #endregion

                                #region Create folder
                                if (IsExsit)
                                {
                                    Guid uniqueID = Guid.NewGuid();
                                    byte[] bArr = uniqueID.ToByteArray();
                                    int autonum = BitConverter.ToInt32(bArr, 0);

                                    CrrFolder.SubFolders.Add(CrrFolder.ServerRelativeUrl + "/" + strToFolderName + "(" + autonum.ToString() + ")");
                                }
                                else
                                {
                                    CrrFolder.SubFolders.Add(CrrFolder.ServerRelativeUrl + "/" + strToFolderName);
                                }
                                #endregion
                            }
                        }
                    }

                    #region Log
                    aType = SquareActivities.SquareDocFolderCreate;
                    bSave = sHelper.SaveActivity(this.Page, aType, string.Format(GetTextResource("SquareRes", "SquareDocFolderCreate"), strToFolderName)); //"xxx님이 xxx폴더를 생성했습니다.");
                    #endregion
                }
                #endregion
                #region 아이템 삭제
                if (strEventType == "4")
                {
                    string strItemName = string.Empty;
                    //string strItemType = string.Empty;

                    using (SPSite _site = new SPSite(strListUrl))
                    {
                        using (SPWeb _web = _site.OpenWeb(strListUrl))
                        {
                            SPList _list = _web.GetList(strListUrl);
                            SPListItemCollection _items = _list.Items;
                            SPListItem _item = _list.GetItemById(Convert.ToInt32(strFromDocID));
                            strItemName = _item.Name;
                            //strItemType = _item["ContentType"].ToString();
                            _item.Delete();
                        }
                    }

                    #region Log
                    aType = SquareActivities.SquareDocItemRemove;
                    bSave = sHelper.SaveActivity(this.Page, aType, string.Format(GetTextResource("SquareRes", "SquareDocItemRemove"), strItemName, ".")); //"xxx님이 xxx 문서(폴더)를 삭제하였습니다.");
                    #endregion
                }
                #endregion
                #region //기타
                else
                {
                }
                #endregion
            }
            catch (Exception)
            {
            }
            finally
            {
                Default();                
            }
        }
        #endregion

        #endregion

        #region Event

        #region public void btnFolderAdd_Click(object sender, EventArgs e)
        /// <summary>
        /// 폴더 추가 이벤트
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void btnFolderAdd_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(this.hdEventType.Value) && !string.IsNullOrEmpty(this.hdToFolderName.Value))
            {
                applySetting(hdEventType.Value, hdFromSiteUrl.Value, hdFromWebName.Value, hdFromListUrl.Value, hdFromDocID.Value, hdToSiteUrl.Value, hdToWebName.Value, hdToListUrl.Value, hdToFolderName.Value);
            }            
        }
        #endregion

        #region public void btnSave_Click(object sender, EventArgs e)
        /// <summary>
        /// 문서 이동, 폴더 생성 등 적용버튼
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void btnSave_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(this.hdEventType.Value)
                && !string.IsNullOrEmpty(this.hdFromSiteUrl.Value)
                && !string.IsNullOrEmpty(this.hdFromWebName.Value)
                && !string.IsNullOrEmpty(this.hdFromListUrl.Value)
                && !string.IsNullOrEmpty(this.hdFromDocID.Value)
                && !string.IsNullOrEmpty(this.hdToSiteUrl.Value)
                && !string.IsNullOrEmpty(this.hdToWebName.Value)
                && !string.IsNullOrEmpty(this.hdToListUrl.Value)
                && !string.IsNullOrEmpty(this.hdToFolderName.Value))
            {
                applySetting(hdEventType.Value, hdFromSiteUrl.Value, hdFromWebName.Value, hdFromListUrl.Value, hdFromDocID.Value, hdToSiteUrl.Value, hdToWebName.Value, hdToListUrl.Value, hdToFolderName.Value);
            }
        }
        #endregion

        #region public void btnDelete_Click(object sender, EventArgs e)
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void btnDelete_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(this.hdEventType.Value) && !string.IsNullOrEmpty(this.hdFromDocID.Value))
            {
                applySetting(hdEventType.Value, hdFromSiteUrl.Value, hdFromWebName.Value, hdFromListUrl.Value, hdFromDocID.Value, hdToSiteUrl.Value, hdToWebName.Value, hdToListUrl.Value, hdToFolderName.Value);
            }
        }
        #endregion

        #region public void btnViewIcon_Click(object sender, EventArgs e)
        /// <summary>
        /// 아이콘보기 버튼 클릭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void btnViewIcon_Click(object sender, EventArgs e)
        {
            ViewState["type_listview"] = "thumb";
            GetData();
        }
        #endregion

        #region public void btnViewDetail_Click(object sender, EventArgs e)
        /// <summary>
        /// 자세히보기 버튼 클릭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void btnViewDetail_Click(object sender, EventArgs e)
        {
            ViewState["type_listview"] = "detail";
            GetData();
        }
        #endregion

        #region public void btnLocation_Click(object sender, EventArgs e)
        /// <summary>
        /// 폴더 클릭 시 위치 변경 이벤트
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void btnLocation_Click(object sender, EventArgs e)
        {
            ViewState["crrfolder_location"] = null;
            ViewState["crrfolder_depth"] = null;

            ViewState["crrfolder_location"] = strConvertToString(this.hdfolderLocation.Value);
            ViewState["crrfolder_depth"] = strConvertToString(this.hdfolderDepth.Value);

            Default();
        }
        #endregion

        #region public void btnDummy_Click(object sender, EventArgs e)
        /// <summary>
        /// 폴더 클릭 시 위치 변경 이벤트
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void btnDummy_Click(object sender, EventArgs e)
        {
            Default();
        }
        #endregion        

        #endregion
    }
}